package v1

import (
	"gin-ebook/Models"
	"gin-ebook/pkg/e"
	"gin-ebook/pkg/util"
	"log"
)

// @Summary 登录
// @Produce  json
// @Tags Login
// @Param username query string true "username"  maxlength(100)
// @Param password query string true "password"
// @Success 200 {string} string "{"code":200,"data":{},"msg":"ok"}"
// @Router /auth [get]
func GetAuth(username string, password string) (code int, token string, result map[string]interface{}) {
	log.Println(username)
	result = make(map[string]interface{})

	// 首先判断是否存在用户
	isExist := models.CheckAuth(username, password)
	if isExist {
		// 用户存在生成密钥并返回
		var err error
		token, err = util.GenerateToken(username, password)
		if err != nil {
			code = e.ERROR_AUTH_TOKEN
		} else {
			result = models.GetAuth(username, password)
			code = e.SUCCESS
		}
	} else {
		code = e.ERROR_AUTH
	}

	return
}

// @Summary 增加用户
// @Produce  json
// @Tags User
// @Param username query string true "username"  maxlength(100)
// @Param password query string true "password"
// @Success 200 {string} string "{"code":200,"data":{},"msg":"ok"}"
// @Router /auth [post]
func AddAuth(username string, password string) (code int) {

	isExist := models.CheckAuth(username, password)
	if isExist {
		code = e.ERROR_EXIST_AUTH

	} else {
		code = e.SUCCESS
		models.AddAuth(username, password)
	}

	return
}
